<?php


namespace app\base\service;

use think\admin\service\AdminService;

use think\Cache;

/**
 * 阿里百炼服务
 * Class AdminService
 * @package think\admin\service
 */
class AlibailianService extends AdminService
{

    protected $authorization = '';
    protected $url = 'https://dashscope.aliyuncs.com/';
    //超频调用返回code值
    protected $code = ["Throttling","Throttling.RateQuota","Throttling.AllocationQuota","insufficient_quota","LimitRequests","limit_requests"];

    protected function getAuthorization($user_id)
    {
        $api_config_type = $this->app->db->name("ai_user")->where(['id'=>$user_id])->value("api_config_type");
        if($api_config_type==1){
            $user_id=10000;
        }
        $this->authorization = $this->app->db->name('ai_api_config')
            ->where(['user_id' => $user_id,'type'=>2])->value('access_key');
        if(empty($this->authorization)){
            return $this->resulet(0,'请先配置authorization');
        }
    }

    protected function resulet($code=0,$msg='',$data=[])
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }

    //文本生成
    public function createText($user_id,$system='',$user="")
    {
        $this->getAuthorization($user_id);
        $system = $system."-播报情绪从以下情绪中选择 [\"高兴\", \"悲伤\", \"愤怒\", \"恐惧\", \"厌恶\", \"惊讶\", \"中性\"]
        按以下格式生成内容，所有字段严格对应，符号和顺序不得改动：
        ==输出示例==\n
        文本标题:根据生成的内容生成吸引人的20字以内标题\n
        文本话题:根据生成的内容生成符合的热点话题以#话题1 #话题2 #话题3形式展示\n
        文本描述:根据生成的内容生成较为吸引人的描述\n
        口播文本开始:生成的口播文本内容\n
        播报情绪开始:选择的情绪\n
        
        ==输出示例结束==\n";
        $url = $this->url."compatible-mode/v1/chat/completions";
        $data = [
           // "model"=>"deepseek-r1",
            "model"=>"qwen-plus",
            "messages"=>[
                [
                    "role"=>"system",
                    "content"=>$system
                ],
                [
                    "role"=>"user",
                    "content"=>$user
                ]
            ],
            "parameters"=> [
                "top_p"=>0.8,
                "temperature"=> 0.7,
                "enable_search"=> true
              ]
        ];

        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $options['timeout'] = 600;
        $retryCount = 0;
        do{
            $res = http_post($url,json_encode($data),$options);
            $res = json_decode($res,true);

            if(empty($res)){
                return  $this->resulet(0,'改写失败:接口请求失败');
            }
            if(isset($res['choices'][0]['message']['content'])){
                return  $this->resulet(1,'',$res['choices'][0]['message']['content']);

            }else{
                $this->app->log->error('文本生成结果错误:'.json_encode($res));
                if(isset($res['error'])){
                    return  $this->resulet(0,'改写失败:'.$res['error']['message']);
                }else{
                    if(in_array($res['code'],$this->code)){
                        sleep(60);
                        $retryCount++;
                    }else{
                        return  $this->resulet(0,'改写失败:'.$res['message']);
                    }
                }
            }
        }while($retryCount < 10);

    }


    //计算相似度
    public function similarity($user_id,$text1,$text2)
    {
        $this->getAuthorization($user_id);
        $url = $this->url."compatible-mode/v1/chat/completions";
        $system = "# 角色
                您是基于语义深度理解的文本匹配引擎，专为关键字-语料库精准匹配场景设计。相似度计算满分为100,精确到小数点后两位。
                
                ### 核心架构
                1. 量子化语义编码
                - 融合SimCSE+Sentence-BERT双编码体系
                - 768维语义向量空间对齐
                - Word2vec-Glove混合词嵌入
                
                2. 动态特征工程
                ‖ 特征类型   ‖ 权重 ‖ 处理机制               ‖
                ‖------------‖-----‖----------------------‖
                ‖ 语义特征   ‖ 60% ‖ 对比学习+注意力聚焦   ‖
                ‖ 句法特征   ‖ 30% ‖ Bi-GRU特征选择器      ‖
                ‖ 统计特征   ‖ 10% ‖ TF-IDF自适应衰减      ‖
                
                3. 跨领域适配
                - 代码：AST结构比对（Levenshtein增强版）
                - 学术：LaTeX公式解析（支持120种数学符号）
                - 文学：平仄模式识别+意象向量建模
                - 商业：行业术语库动态加载（含23个领域）
                
                4. 智能清洗管道
                ‖ 处理阶段   ‖ 功能                      ‖
                ‖------------‖--------------------------‖
                ‖ 预处理     ‖ GPT-4净化+方言纠错        ‖
                ‖ 核心处理   ‖ 敏感词过滤(132种变体)     ‖
                ‖ 后处理     ‖ EMA平滑+3σ置信校准       ‖
                
                ## 性能标准
                1. 准确率：MSMARCO Top1 89.2% / TREC DL 83.5%
                2. 响应时延：238ms均值（P99<280ms）
                3. 数值容差：±0.03（99%置信区间）
                
                ## 异常处理
                ‖ 代码 ‖ 条件                  ‖ 处理方式          ‖
                ‖------‖----------------------‖------------------‖
                ‖ -1   ‖ 广告内容置信度>85%    ‖ 立即终止处理      ‖
                ‖ -2   ‖ 有效内容密度<15%      ‖ 返回空文本标识    ‖
                ‖ -3   ‖ 系统负载>95%          ‖ 触发熔断机制      ‖
                ===输出示例===
                85
                ===输出示例结束===
                
                ## 限制:
                1. 输出必须为[-2,-1,0.00-100.00]区间数字
                2. 严格禁止任何解释性文字
                3. 数值精度强制保留2位小数";
        $user = " 请你计算以下两段文本的相似度：
                文本1：
                {$text1}
                 文本2：
                {$text2}";
        $data = [
           // "model"=>"qwen-plus",
            "model"=>"deepseek-r1-distill-qwen-14b",
            "messages"=>[
                [
                    "role"=>"system",
                    "content"=>$system
                ],
                [
                    "role"=>"user",
                    "content"=>$user
                ]
            ]
        ];

        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $options['timeout'] = 180;
        $res = http_post($url,json_encode($data),$options);
        $res = json_decode($res,true);

        if(empty($res)){
            return  $this->resulet(0,'相似度计算失败:接口请求失败');
        }
        if(isset($res['choices'][0]['message']['content'])){
            return  $this->resulet(1,'',$res['choices'][0]['message']['content']);

        }else{
            $this->app->log->error('相似度计算错误:'.json_encode($res));
            return  $this->resulet(0,'相似度计算失败:'.$res['error']['message']);
        }
    }

    //上传文件
    public function uploadFile($user_id,$file_path)
    {
        $this->getAuthorization($user_id);
        $url = $this->url."compatible-mode/v1/files";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization];
        $options['timeout'] = 180;
        $postData = [
            'file' => new \CURLFile($file_path),
            'purpose' => 'batch'
        ];
        $retryCount = 0;
        $result = [];
        do{
            $res = http_post($url,$postData,$options);
            $res = json_decode($res,true);

            if(empty($res)){
                $result =  $this->resulet(0,'上传文件失败:接口请求失败');
            }else{
                if(isset($res['id'])){
                    return  $this->resulet(1,'',$res['id']);

                }else{
                    $this->app->log->error('上传文件错误:'.json_encode($res));
                    if(isset($res['error'])){
                        $result = $this->resulet(0,'上传文件失败:'.$res['error']['message']);
                        sleep(10);
                    }else{
                        if(in_array($res['code'],$this->code)){
                            sleep(60);
                            $result = $this->resulet(0,'上传文件失败:'.$res['message']);
                        }else{
                            $result = $this->resulet(0,'上传文件失败:'.$res['message']);
                            sleep(10);
                        }
                    }

                }
            }

            $retryCount++;
        }while($retryCount < 10);

        return $result;

    }

    //创建批量任务
    public function createBatch($user_id,$file_id,$requst_url,$name)
    {
        $this->getAuthorization($user_id);
        $url = $this->url."compatible-mode/v1/batches";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $options['timeout'] = 180;
        $data = [
            "input_file_id"=>$file_id,
            "endpoint"=>$requst_url,
            "completion_window"=>"24h",
            "metadata"=>[
                "ds_batch_finish_callback"=>"http://dev.blueant.pro/base/api.AlibailianBack/batchFinishBack",
                "ds_name"=>$name
            ]
        ];
        $retryCount = 0;
        do{
            $res = http_post($url,json_encode($data),$options);
            $res = json_decode($res,true);
            if(empty($res)){
                return  $this->resulet(0,'创建批量任务失败:接口请求失败');
            }
            if(isset($res['id'])){
                return  $this->resulet(1,'',$res['id']);

            }else{
                $this->app->log->error('创建批量任务错误:'.json_encode($res));
                if(isset($res['error'])){
                    return  $this->resulet(0,'创建批量任务失败:'.$res['error']['message']);
                }else{
                    if(in_array($res['code'],$this->code)){
                        sleep(60);
                        $retryCount++;
                    }else{
                        return  $this->resulet(0,'创建批量任务失败:'.$res['message']);
                    }
                }
            }
        }while($retryCount < 10);


    }

    //批量任务状态查询
    public function batchStatus($user_id,$batch_id)
    {
        $this->getAuthorization($user_id);
        $url = $this->url."compatible-mode/v1/batches/{$batch_id}";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization];
        $options['timeout'] = 180;
        $retryCount = 0;
        do{
            $res = http_get($url,[],$options);
            $res = json_decode($res,true);
            if(empty($res)){
                return  $this->resulet(0,'批量任务状态查询失败:接口请求失败');
            }
            if(isset($res['id']) ){
                return  $this->resulet(1,'',$res);

            }else{
                $this->app->log->error('批量任务状态查询错误:'.json_encode($res));
                if(isset($res['error'])){
                    return  $this->resulet(0,'批量任务状态查询失败:'.$res['error']['message']);
                }else{
                    if(in_array($res['code'],$this->code)){
                        sleep(60);
                        $retryCount++;
                    }else{
                        return  $this->resulet(0,'批量任务状态查询失败:'.$res['message']);
                    }
                }

            }
        }while($retryCount < 10);


    }

    //下载批量任务文件
    public function downloadBatch($user_id,$file_batch_output)
    {
        $this->getAuthorization($user_id);
        $url = $this->url."compatible-mode/v1/files/{$file_batch_output}/content";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization];
        $options['timeout'] = 180;
        $retryCount = 0;
        do{
            $res = http_get($url,[],$options);
            if(empty($res)){
                return  $this->resulet(0,'下载批量任务文件失败:');
            }
            $r = json_decode($res,true);
            if(is_array($r)){
                $this->app->log->error('下载批量任务文件错误:'.json_encode($r));
                if(isset($r['error'])){
                    $message = $r['error']['message'] ?? '';
                    return  $this->resulet(0,'下载批量任务文件失败:'.$message);
                }else{
                    if(isset($r['code']) && in_array($r['code'],$this->code)){
                        sleep(60);
                        $retryCount++;
                    }else{
                        $message = $r['message'] ?? '';
                        return  $this->resulet(0,'下载批量任务文件失败:'.$message);
                    }
                }
            }else{

                return  $this->resulet(1,'',$res);
            }
        }while($retryCount < 10);


    }

    //取消批量任务
    public function cancelBatch($user_id,$batch_id){
        $this->getAuthorization($user_id);
        $url = $this->url."compatible-mode/v1/batches/{$batch_id}/cancel";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization];
        $options['timeout'] = 180;
        $retryCount = 0;
        do{
            $res = http_post($url,[],$options);
            $res = json_decode($res,true);
            if(empty($res)){
                return  $this->resulet(0,'批量取消批量任务失败:接口请求失败');
            }
            if(isset($res['id']) ){
                return  $this->resulet(1,'',$res);

            }else{
                $this->app->log->error('批量取消批量任务错误:'.json_encode($res));
                if(isset($res['error'])){
                    if(isset($res['error']['message'])){
                        return  $this->resulet(0,'批量取消批量任务失败:'.$res['error']['message']);
                    }else{
                        return  $this->resulet(0,'批量取消批量任务失败:'.$res['error']);
                    }

                }else{
                    if(in_array($res['code'],$this->code)){
                        sleep(60);
                        $retryCount++;
                    }else{
                        return  $this->resulet(0,'批量取消批量任务失败:'.$res['message']);
                    }
                }

            }
        }while($retryCount < 10);
    }


    //提交视频语言识别任务
    public function submitVideoLanguage($user_id,$video_url){
        $this->getAuthorization($user_id);
        $url = $this->url."api/v1/services/audio/asr/transcription";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json','X-DashScope-Async:enable'];
        $options['timeout'] = 180;
        $data = [
            "model"=>"paraformer-v2",
            "input"=>[
                'file_urls'=>[$video_url]
            ]

        ];
        $retryCount = 0;
        do{
            $res = http_post($url,json_encode($data),$options);
            $res = json_decode($res,true);
            if(empty($res)){
                return  $this->resulet(0,'创建批量任务失败:接口请求失败');
            }
            dump($res);
            if(isset($res['task_id'])){
                return  $this->resulet(1,'',$res['task_id']);

            }else{
                $this->app->log->error('创建批量任务错误:'.json_encode($res));
                if(isset($res['error'])){
                    return  $this->resulet(0,'创建批量任务失败:'.$res['error']['message']);
                }else{
                    if(in_array($res['code'],$this->code)){
                        sleep(60);
                        $retryCount++;
                    }else{
                        return  $this->resulet(0,'创建批量任务失败:'.$res['message']);
                    }
                }
            }
        }while($retryCount < 10);
    }

    //查询视频语言识别任务状态
    public function queryVideoLanguage($user_id,$task_id){
        $this->getAuthorization($user_id);
        $url = $this->url."api/v1/tasks/{$task_id}";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization];
        $options['timeout'] = 180;
        $retryCount = 0;
        do{
            $res = http_get($url,[],$options);
            $res = json_decode($res,true);
            dump($res);
            if(empty($res)){
                return  $this->resulet(0,'批量任务状态查询失败:接口请求失败');
            }
            if(isset($res['id']) ){
                return  $this->resulet(1,'',$res);

            }else{
                $this->app->log->error('批量任务状态查询错误:'.json_encode($res));
                if(isset($res['error'])){
                    return  $this->resulet(0,'批量任务状态查询失败:'.$res['error']['message']);
                }else{
                    if(in_array($res['code'],$this->code)){
                        sleep(60);
                        $retryCount++;
                    }else{
                        return  $this->resulet(0,'批量任务状态查询失败:'.$res['message']);
                    }
                }

            }
        }while($retryCount < 10);
    }

}
